package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: UploadService
 * @Description: 文件上传服务
 * @Author: sunt
 * @Date: 2019/11/12 14:58
 * @Version 1.0
 **/
@Service
@Slf4j
public class UploadService {

    @Value("${image.server.baseUrl}")
    private String imageUrl;

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg","image/jpg","image/bpmn");

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上传
     * @param file
     * @return
     */
    public String upload(MultipartFile file) throws IOException {
        //获取文件类型
        String contentType = file.getContentType();
        if(!suffixes.contains(contentType)) {
            log.info("上传失败,文件类型:" + contentType + "不匹配");
            return null;
        }
        //校验上传内容大小
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if(null == bufferedImage) {
            log.info("上传失败,文件内容有误");
            return null;
        }
        //上传到FastDFS
        String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        // 2.2、上传
        StorePath storePath = fastFileStorageClient.uploadFile(
                file.getInputStream(), file.getSize(), extension, null);
        // 2.3、返回完整路径
        return imageUrl + storePath.getFullPath();
    }
}
